package controllers;

import apidocs.ApiService;
import apidocs.ApiUtils;
import apidocs.Configs;
import org.apache.commons.lang.StringUtils;
import play.Play;
import play.mvc.Before;
import play.mvc.Controller;
import play.vfs.VirtualFile;
import utils.ApiUtil;

import java.util.List;

/**
 * @author zhangzc
 * @since 5/18/18
 */
public class BaseCommonController extends Controller{

    public static final String SessionKey_login = "GODTEAM";

    @Before(unless = {"login", "auth"})
    static void checkAccess() {
        String enable = Configs.getAsString("apidoc", "enable");
        if (!StringUtils.equalsIgnoreCase("enable", enable)) { //如果在正式环境，则不允许使用
            forbidden("Only available when apidoc=enable");
        }

        String secure = Configs.getAsString("apidoc.user", "disable");

        if (StringUtils.equalsIgnoreCase("enable", secure) && !session.contains(SessionKey_login)) { //如果在正式环境，则不允许使用
            login();
        }

        boolean isAdmin = false;
        String[] admins = Configs.getAsStringArray("apidoc.admin");
        for(String admin : admins){
            if(StringUtils.equals(session.get(SessionKey_login), admin)){
                isAdmin = true;
                break;
            }
        }

        renderArgs.put("isAdmin", isAdmin);

        //获取项目根目录的apidoc.json
        renderArgs.put("apiJsonList", ApiUtils.getApiJson());

        //获取全部的标记了@ApiService的Controller
        List<Class> apiClassList = ApiUtil.getPermApiList(Play.classloader.getAnnotatedClasses(ApiService.class));
        renderArgs.put("apiClassList", apiClassList);

        //获取文档首页文件
        VirtualFile indexFile = Play.getVirtualFile("apidoc.md");
        renderArgs.put("indexFile", indexFile);

        //获取文档首页文件
        VirtualFile docDir = Play.getVirtualFile("apidoc");
        renderArgs.put("docDir", docDir);

        boolean isSearchEnable = StringUtils.equalsIgnoreCase("enable", Play.configuration.getProperty("apidoc.search", "disable"));
        renderArgs.put("isSearchEnable", isSearchEnable);
    }

    public static void login() {
        render();
    }

    public static void auth(String name, String pwd) {
        name = StringUtils.trimToEmpty(name);
        pwd = StringUtils.trimToEmpty(pwd);
        String password = Play.configuration.getProperty("apidoc.user." + name, "");
        if (StringUtils.isEmpty(password)) {
            login();
        }
        if (!StringUtils.equals(pwd, password)) {
            login();
        }
        session.put(SessionKey_login, name);
        ApiDoc.index();
    }

    public static void quit() {
        session.remove(SessionKey_login);
        login();
    }
}
